package edu.ucsd.ccdb;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

public class CollapsiblePanel extends JPanel {

	private static final long serialVersionUID = 1L;
	
	private class TitlePanel extends JPanel
	{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		private Color fadeto= new Color(200,212,247);
	
		public TitlePanel(LayoutManager layout) {
			super(layout);
		}
	
		protected void paintComponent(Graphics g) 
		{
			GradientPaint gradient=
				new GradientPaint(
					0, 0, Color.white, 
					getSize().width -10, getSize().height, fadeto,
					true);
	
			Graphics2D g2d = (Graphics2D) g;
			g2d.setPaint(gradient);
			g2d.fill(new Rectangle(getSize().width, getSize().height));
		}
	}
	
	private JPanel mPanel= new JPanel(new GridLayout(0,1,2,2));
	private JLabel mTitle;
	private JLabel mButton;
	
	public CollapsiblePanel(String title)
	{
		setLayout(new BorderLayout());
	
		final Color active= new Color(66,142,255);
		final Color inactive= new Color(33,93,198);
//		final ImageIcon up= new ImageIcon("up.gif");
		final ImageIcon up= createImageIcon ("/images/up.gif");
		
		final ImageIcon down= createImageIcon ("/images/down.gif");
	
		mTitle= new JLabel(title);
		mTitle.setForeground(inactive);
		mButton= new JLabel(up);
	
		TitlePanel panel= new TitlePanel(new BorderLayout()); 
		panel.setBorder(new EmptyBorder(2,2,2,2));
		panel.add(mTitle, BorderLayout.CENTER);
		panel.add(mButton, BorderLayout.EAST);
	
		panel.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				mPanel.setVisible(!mPanel.isVisible());
				mButton.setIcon(mPanel.isVisible() ? up : down);
			}
			public void mouseEntered(MouseEvent e) {
				mTitle.setForeground(active);
			}
			public void mouseExited(MouseEvent e) {
				mTitle.setForeground(inactive);
			}
		});
	
		panel.setBackground(Color.WHITE);
	
		mPanel.setBorder(new EmptyBorder(2,2,2,2));
		mPanel.setBackground(new Color(214,223,247));
	
		add(panel, BorderLayout.NORTH);
		add(mPanel, BorderLayout.CENTER);
	}
	
	public Component add(Component comp)
	{
		return mPanel.add(comp);
	}
	
	private ImageIcon createImageIcon (String path) {
		URL imageURL = TreePanel.class.getResource(path);
		
		if (imageURL != null ){
			return new ImageIcon(imageURL);
		}
		System.out.println ("Invalid path");
		return null;
	}
}
